<template>
  <BasicModal
    :footer="null"
    :title="isShow ? '查看位置' : '请点选位置'"
    v-bind="$attrs"
    :class="prefixCls"
    @register="register"
    :width="760"
    :destroyOnClose="true"
  >
    <div :class="{ 'h-400px': !isShow, 'h-370px': isShow, 'flex flex-col justify-center': true }">
      <div></div>
      <Row class="w-full h-370px" style="overflow-y: auto">
        <div id="container" class="w-full h-300px"></div>
        <div id="address" v-show="!isShow" class="w-full" style="border: 1px solid #eee">
          <Input :value="curAddr" class="w-full" placeholder="请选择位置" readonly />
          <div
            v-show="false"
            v-for="(item, index) in items"
            :key="item.uid"
            :title="item.address"
            class="pl-2 cursor-pointer"
            @click="handleClick(item)"
          >
            {{ item.title }}</div
          >
        </div>
      </Row>
      <div :class="`${prefixCls}__footer mt-5`" v-if="!isShow">
        <a-button type="primary" size="middle" @click="handleOk"> 确定 </a-button>
        <a-button type="primary" size="middle" class="ml-2" @click="handleCancel"> 取消 </a-button>
      </div>
      <div :class="`${prefixCls}__footer mt-5`" v-else>
        <a-button type="primary" size="middle" class="ml-2" @click="handleCancel"> 关闭 </a-button>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { Row, Col, Input } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal/index';
  import { buildUUID } from '/@/utils/uuid';

  export default defineComponent({
    name: 'LocationMarkModal',
    components: { BasicModal, Row, Col, Input },
    emits: ['register', 'success'],
    setup(_, { emit }) {
      const { t } = useI18n();
      const { prefixCls } = useDesign('header-lock-modal');
      const items = ref([]);
      const curAddr = ref('');
      const isShow = ref(true);
      const title = ref('');
      const { createMessage } = useMessage();

      // if (!navigator.onLine) {
      //   console.log('The network is offline');
      //   return;
      // } else {
      //   console.log('The network is online');
      // }

      if (typeof T == 'undefined') {
        console.error('天地图对象T未定义, 请检查网络联接');
        return;
      }

      let map;
      let zoom = 12;

      function loadMap(isLocated, lng, lat) {
        //初始化地图对象
        map = new T.Map('container');
        //设置显示地图的中心点和级别
        map.centerAndZoom(new T.LngLat(lng, lat), zoom); // 南京
        //创建地图类型控件对象
        // let _mapType = new T.Control.MapType();

        // //添加地图类型控件
        // map.addControl(_mapType);

        //创建缩放平移控件对象
        let _zoomControl = new T.Control.Zoom();

        //添加缩放平移控件
        map.addControl(_zoomControl);

        //创建缩放平移控件对象
        _zoomControl.setPosition(T_ANCHOR_TOP_LEFT);

        //创建右键菜单对象
        var menu = new T.ContextMenu({
          width: 140,
        });

        //添加右键菜单
        var txtMenuItem = [
          {
            text: '放大',
            callback: function () {
              map.zoomIn();
            },
          },
          {
            text: '缩小',
            callback: function () {
              map.zoomOut();
            },
          },
          {
            text: '放到最大',
            callback: function () {
              map.setZoom(18);
            },
          },
          {
            text: '查看全国',
            callback: function () {
              map.setZoom(4);
            },
          },
          // {
          //   text: '获得右键点击处坐标',
          //   isDisable: false,
          //   callback: function (lnglat) {
          //     console.log(lnglat.getLng() + ',' + lnglat.getLat());
          //     geocode.getLocation(lnglat, searchResult);
          //   },
          // },
        ];

        for (var i = 0; i < txtMenuItem.length; i++) {
          //添加菜单项
          var item = new T.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback);
          //item.disable();
          menu.addItem(item);
          if (i == 1 || i == 3) {
            //添加分割线
            menu.addSeparator();
          }
        }

        //装载菜单
        map.addContextMenu(menu);

        // 创建定位对象
        let lo = new T.Geolocation();
        let fn = function (e) {
          //当前为移动端时
          if (this.getStatus() == 0) {
            map.centerAndZoom(e.lnglat, 15);
            console.log('获取定位坐标：' + e.lnglat.lng + ',' + e.lnglat.lat);
            // var marker = new T.Marker(e.lnglat);
            // map.addOverLay(marker);
          }
          //当前为PC端时
          if (this.getStatus() == 1) {
            map.centerAndZoom(e.lnglat, e.level);
            console.log('获取定位坐标：' + e.lnglat.lng + ',' + e.lnglat.lat);
            // var marker = new T.Marker(e.lnglat);
            // map.addOverLay(marker);
          }
        };
        if (!isLocated) {
          lo.getCurrentPosition(fn);
        }
      }

      //创建对象
      let geocode = new T.Geocoder();
      function addMapClick() {
        removeMapClick();
        map.addEventListener('click', mapClick);
      }

      function removeMapClick() {
        map.removeEventListener('click', mapClick);
      }

      function mapClick(e) {
        console.log(e.lnglat.getLng() + ',' + e.lnglat.getLat());
        geocode.getLocation(e.lnglat, searchResult);
        setMarker(e.lnglat.getLng(), e.lnglat.getLat());
      }

      function searchResult(result) {
        if (result.getStatus() == 0) {
          console.log(result.getAddress());
          let addressComponent = result.getAddressComponent();
          let item = {
            uuid: buildUUID(20),
            address: result.getAddress(),
            title: addressComponent.poi,
            point: { lng: result.location.lon, lat: result.location.lat },
          };
          curItem = item;
          curAddr.value = item.address;
          items.value = [item];
        } else {
          console.error('服务器返回状态：' + result.getStatus());
          createMessage.warn(result.getMsg());
        }
      }

      //设置标注
      function setMarker(lng, lat) {
        map.clearOverLays();
        var marker = new T.Marker(new T.LngLat(lng, lat));
        //向地图上添加标注
        map.addOverLay(marker);
      }

      const [register, { closeModal }] = useModalInner(async (data) => {
        console.log('data', data);
        let lng = 116.40969;
        let lat = 39.89945; // 天安门
        let maps = data.maps;
        console.log('maps', maps);
        isShow.value = data.isShow;

        let isLocated = false;
        if (maps) {
          let mapArr = maps.split(',');
          console.log('mapArr', mapArr);
          if (mapArr != null && mapArr.length == 3) {
            lng = mapArr[0];
            lat = mapArr[1];
            curAddr.value = mapArr[2];
            isLocated = true;
          }
        }

        loadMap(isLocated, lng, lat);
        if (isLocated) {
          setMarker(lng, lat);
        }

        addMapClick();

        if (!isShow.value) {
          title.value = '请点选位置';
        } else {
          title.value = '查看位置';
        }
      });

      if (typeof T.Map == 'undefined') {
        console.error('天地图对象T.Map未定义, 请检查网络联接');
        return;
      }

      let curItem = {};
      function handleClick(item) {
        console.log('handleClick item', item);
        curAddr.value = item.address;
        curItem = item;
      }

      async function handleOk() {
        if (!curAddr.value) {
          createMessage.warn('请选择位置');
          return;
        }
        closeModal();
        emit('success', curItem);
      }

      async function handleCancel() {
        curAddr.value = '';
        closeModal();
      }

      return {
        t,
        prefixCls,
        register,
        handleOk,
        handleCancel,
        items,
        handleClick,
        curAddr,
        isShow,
        title,
      };
    },
  });
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-header-lock-modal';

  .@{prefix-cls} {
    &__entry {
      position: relative;
      //height: 240px;
      padding: 130px 30px 30px;
      border-radius: 10px;
    }

    &__header {
      position: absolute;
      top: 0;
      left: calc(50% - 45px);
      width: auto;
      text-align: center;

      &-name {
        margin-top: 5px;
      }
    }

    &__footer {
      text-align: center;
    }
  }

  .BMap_Marker img {
    max-width: max-content;
  }

  .tdt-control {
    display: none;
  }
</style>
